package com.cn.customer.housekeeping.housekeepingb.ui;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.cn.customer.housekeeping.housekeepingb.R;
import com.cn.customer.housekeeping.housekeepingb.bean.BaseResp;
import com.cn.customer.housekeeping.housekeepingb.bean.OrderPayResp;
import com.cn.customer.housekeeping.housekeepingb.bean.PayParameterResp;
import com.cn.customer.housekeeping.housekeepingb.bean.ZBOrderPayResp;
import com.cn.customer.housekeeping.housekeepingb.biz.personcenter.IUserLoginView;
import com.cn.customer.housekeeping.housekeepingb.biz.personcenter.InterfacePresenter;
import com.cn.customer.housekeeping.housekeepingb.constant.Constants;
import com.cn.customer.housekeeping.housekeepingb.constant.URLUtil;
import com.cn.customer.housekeeping.housekeepingb.eventbus.EvBusWeiXinPayResultState;
import com.cn.customer.housekeeping.housekeepingb.ui.base.BaseActivity;
import com.cn.customer.housekeeping.housekeepingb.util.PayResult;
import com.cn.customer.housekeeping.housekeepingb.util.ToastUtil;
import com.cn.customer.housekeeping.housekeepingb.util.Utils;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/***
 * 支付页面
 */
public class PayActivity extends BaseActivity implements OnClickListener, IUserLoginView {
    private InterfacePresenter interfacePresenter;
    private ListView mListView;
    private ListView mPullToRefreshListView;
    private Dialog mPayDialog;
    private OrderPayWayAdapter mAdapter;
    private int clickPostion = 0;
    private ArrayList<PayModle> payList;
    private RelativeLayout rl_complete;
    private RelativeLayout activity_main;
    private TextView tv_close, tv_login, tv_dia_close;
    private ZBOrderPayResp mZBOrderPayResp;
    private String mBalance = "0";
    private String serviceid;
    private PayParameterResp mPayParameterResp;
    public IWXAPI api;
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        showToast("支付成功");

                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        showToast("支付已取消");
                    } else {
                        showToast("支付失败");
                    }
                    break;
                }
                default:
                    break;
            }
        }

    };


    public void onEvent(EvBusWeiXinPayResultState result) {
        com.tencent.mm.opensdk.modelbase.BaseResp resp = result.getResp();
        switch (resp.errCode) {
            case 0://微信支付成功
                showToast("支付成功");
                break;
            case -1://支付失败
                showToast("支付失败");
                break;
            case -2://用户取消
                showToast("取消支付");
                break;
            default:
                break;
        }

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setFinishOnTouchOutside(true);
        setContentView(R.layout.activity_pay_list);
        getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        super.onCreate(savedInstanceState);


    }

    @Override
    public void initViews() {
        interfacePresenter = new InterfacePresenter();
        interfacePresenter.attachView(this);
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID_WXPAY, false);
        api.registerApp(Constants.APP_ID_WXPAY);
        mListView = (ListView) findViewById(R.id.pull_refresh_list);
        activity_main = (RelativeLayout) findViewById(R.id.activity_main);
        tv_close = (TextView) findViewById(R.id.tv_close);
        tv_login = (TextView) findViewById(R.id.tv_login);
        mListView.setHeaderDividersEnabled(false);
        mListView.setDividerHeight(0);
        setList();
        mAdapter = new OrderPayWayAdapter(this, payList);
        mListView.setAdapter(mAdapter);

    }

    @Override
    public void initListeners() {
        tv_close.setOnClickListener(this);
        tv_login.setOnClickListener(this);
        activity_main.setOnClickListener(this);
    }

    @Override
    public void initData() {
        mPayParameterResp = (PayParameterResp) getIntent().getSerializableExtra(Constants.PayParameterResp);
    }

    private static final int SDK_PAY_FLAG = 1;

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.tv_login:
                if (clickPostion == 0) {//支付宝
                    if (mPayParameterResp != null) {
                        interfacePresenter.getPay(mPayParameterResp.getServiceid(), mPayParameterResp.getOrderid(), mPayParameterResp.getAddress()
                                , mPayParameterResp.getLat(), mPayParameterResp.getLon(), mPayParameterResp.getHoursenum(), mPayParameterResp.getUsername()
                                , mPayParameterResp.getPhone(), mPayParameterResp.getBuytimestamp(), mPayParameterResp.getBuycount(), mPayParameterResp.getComments()
                        );
                    }
                } else if (clickPostion == 1) {//微信
                    ToastUtil.makeText(PayActivity.this, "未开放微信支付");
                    sendPayReq(new OrderPayResp());
                }

                break;
            case R.id.activity_main://点击空白区域
            case R.id.tv_close://选择支付上方关闭按钮
                finish();
                overridePendingTransition(R.anim.slide_out_to_top,
                        R.anim.slide_out_to_bottom);
                break;

            default:
                break;
        }
        super.onClick(arg0);
    }

    public PayReq wxPayReq;

    public void sendPayReq(OrderPayResp mOrderPayResp) {
        if (wxPayReq == null) {
            wxPayReq = new PayReq();
        }
        wxPayReq.appId = mOrderPayResp.getAppid();
        wxPayReq.partnerId = mOrderPayResp.getPartnerid();
        wxPayReq.prepayId = mOrderPayResp.getPrepayid();
        wxPayReq.packageValue = mOrderPayResp.getPackageValue();
        wxPayReq.nonceStr = mOrderPayResp.getNoncestr();
        wxPayReq.timeStamp = mOrderPayResp.getTimestamp();
        wxPayReq.sign = mOrderPayResp.getSign();

// 测试
        wxPayReq.appId = "11111";
        wxPayReq.partnerId = "11111";
        wxPayReq.prepayId = "11111";
        wxPayReq.packageValue = "11111";
        wxPayReq.nonceStr = "11111";
        wxPayReq.timeStamp = "11111";
        wxPayReq.sign = "11111";
        api.sendReq(wxPayReq);
    }

    @Override
    public void setHeader() {
        super.setHeader();
    }


    @Override
    public void onError(BaseResp s) {
        Utils.bequit(s, this);
    }


    @Override
    public void onSuccess(BaseResp s) {
        if (s.getUrl().equals(URLUtil.url_get_pay)) {
            Gson gson = new Gson();
            mZBOrderPayResp = gson.fromJson(s.getData(), ZBOrderPayResp.class);
            if (mZBOrderPayResp.getPaytype().equals("0")) {
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(PayActivity.this);
                        Map<String, String> result = alipay.payV2(mZBOrderPayResp.getOrderInfo(), true);
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);

                    }
                };
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }

        }

    }


    class OrderPayWayAdapter extends BaseAdapter {
        private Context mContext;
        private List<PayModle> mList;

        public OrderPayWayAdapter(Context mContext, List<PayModle> mList) {
            this.mContext = mContext;
            this.mList = mList;
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.activity_pay_item, null);
            TextView payway_texttitle = (TextView) convertView.findViewById(R.id.payway_texttitle);
            TextView payway_balance = (TextView) convertView.findViewById(R.id.payway_balance);

            ImageView payway_image = (ImageView) convertView.findViewById(R.id.payway_image);
            ImageView pay_select_im = (ImageView) convertView.findViewById(R.id.pay_select_im);
            RelativeLayout pay_item_layout = (RelativeLayout) convertView.findViewById(R.id.pay_item_layout);
            payway_texttitle.setText(mList.get(position).getTitle().toString());
            if (mList.get(position).getTitle().toString().equals("微信")) {
                payway_image.setImageResource(R.mipmap.icon_pay_weixin);
            } else if (mList.get(position).getTitle().toString().equals("支付宝")) {
                payway_image.setImageResource(R.mipmap.icon_pay_zhifubao);
            }

            if (mList.get(position).isSelect()) {
                pay_select_im.setImageResource(R.mipmap.icon_pay_selected);
            } else {
                pay_select_im.setImageResource(R.mipmap.em_dx_checkbox_off);
            }
//            if (position == 0) {
//                payway_balance.setVisibility(View.VISIBLE);
//                payway_balance.setText("剩余" + mBalance);
//            } else {
//                payway_balance.setVisibility(View.GONE);
//            }

            pay_item_layout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    resetPayList(position);
                    clickPostion = position;
                }
            });

            return convertView;
        }
    }


    public class PayModle {
        private String title;
        private boolean isSelect;

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public boolean isSelect() {
            return isSelect;
        }

        public void setIsSelect(boolean isSelect) {
            this.isSelect = isSelect;
        }
    }


    private void setList() {
        payList = new ArrayList<PayModle>();

        PayModle modle2 = new PayModle();
        modle2.setTitle("微信");
        modle2.setIsSelect(false);
        PayModle modle3 = new PayModle();
        modle3.setTitle("支付宝");
        modle3.setIsSelect(true);
        payList.add(modle3);
        payList.add(modle2);


    }

    private void resetPayList(int postion) {
        for (int i = 0; i < payList.size(); i++) {
            if (postion == i) {
                payList.get(i).setIsSelect(true);
            } else {
                payList.get(i).setIsSelect(false);
            }
        }
        mAdapter.notifyDataSetChanged();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
            overridePendingTransition(R.anim.slide_out_to_top,
                    R.anim.slide_out_to_bottom);
            return true;
        }
        return true;
    }


}
